"use client"

import type React from "react"
import { useState, useEffect } from "react"
import { Table, Input, Button, Space, Modal, Form, Select, message } from "antd"
import { EditOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import axios from "axios"

const { Search } = Input

interface Host {
  id: string
  name: string
  ip: string
  group: string
  description?: string
}

const HostsList: React.FC = () => {
  const [hosts, setHosts] = useState<Host[]>([])
  const [loading, setLoading] = useState(false)
  const [searchText, setSearchText] = useState("")
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingHost, setEditingHost] = useState<Host | null>(null)
  const [form] = Form.useForm()

  const fetchHosts = async () => {
    setLoading(true)
    try {
      const response = await axios.get(`http://localhost:3001/api/hosts?search=${searchText}`)
      setHosts(response.data)
    } catch (error) {
      message.error("Failed to fetch hosts")
    }
    setLoading(false)
  }

  useEffect(() => {
    fetchHosts()
  }, [searchText])

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      sorter: (a: Host, b: Host) => a.name.localeCompare(b.name),
    },
    {
      title: "IP",
      dataIndex: "ip",
      key: "ip",
    },
    {
      title: "Group",
      dataIndex: "group",
      key: "group",
      filters: Array.from(new Set(hosts.map((h) => h.group))).map((group) => ({
        text: group,
        value: group,
      })),
      onFilter: (value: string, record: Host) => record.group === value,
    },
    {
      title: "Description",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "Actions",
      key: "actions",
      render: (_: any, record: Host) => (
        <Space>
          <Button
            icon={<EditOutlined />}
            onClick={() => {
              setEditingHost(record)
              form.setFieldsValue(record)
              setIsModalVisible(true)
            }}
          />
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDelete(record.id)} />
        </Space>
      ),
    },
  ]

  const handleDelete = async (id: string) => {
    try {
      await axios.delete(`http://localhost:3001/api/hosts/${id}`)
      message.success("Host deleted successfully")
      fetchHosts()
    } catch (error) {
      message.error("Failed to delete host")
    }
  }

  const handleSubmit = async (values: any) => {
    try {
      if (editingHost) {
        await axios.put(`http://localhost:3001/api/hosts/${editingHost.id}`, values)
        message.success("Host updated successfully")
      } else {
        await axios.post("http://localhost:3001/api/hosts", values)
        message.success("Host added successfully")
      }
      setIsModalVisible(false)
      form.resetFields()
      setEditingHost(null)
      fetchHosts()
    } catch (error) {
      message.error("Operation failed")
    }
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Search
            placeholder="Search hosts..."
            allowClear
            onSearch={(value) => setSearchText(value)}
            style={{ width: 300 }}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingHost(null)
              form.resetFields()
              setIsModalVisible(true)
            }}
          >
            Add Host
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={hosts}
        rowKey="id"
        loading={loading}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `Total ${total} items`,
        }}
      />

      <Modal
        title={editingHost ? "Edit Host" : "Add Host"}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false)
          form.resetFields()
          setEditingHost(null)
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item name="name" label="Name" rules={[{ required: true, message: "Please input the host name!" }]}>
            <Input />
          </Form.Item>
          <Form.Item name="ip" label="IP" rules={[{ required: true, message: "Please input the IP address!" }]}>
            <Input />
          </Form.Item>
          <Form.Item name="group" label="Group" rules={[{ required: true, message: "Please select a group!" }]}>
            <Select>
              {Array.from(new Set(hosts.map((h) => h.group))).map((group) => (
                <Select.Option key={group} value={group}>
                  {group}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default HostsList
